package com.lvmama.monkey.common.utils

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

import org.joda.time.{DateTime, Days}
import org.apache.spark.sql.functions._

/**
  * Created by hejing on 2017/10/12.
  */
object DateUtils {
  /**
    * 计算天数差
    * @param src
    * @param dest
    * @return
    */
  def daysBetween(src:Date,dest:Date): Int ={
    val dateSrc = new DateTime(src)
    val dateDest = new DateTime(dest)
    Days.daysBetween(dateSrc,dateDest).getDays
  }

  def convert2Date(str:String):Date  ={
    val format = new SimpleDateFormat("yyyyMMdd")
    format.parse(str)
  }

  def convert2Str(date:Date):String = {
    val format = new SimpleDateFormat("yyyyMMdd")
    format.format(date)
  }

  def dayOfWeek = udf{(dateStr: String) =>
    val sdf = new SimpleDateFormat("yyyyMMdd")
    val date = sdf.parse(dateStr)
    val cal = Calendar.getInstance()
    cal.setTime(date)
    var w = cal.get(Calendar.DAY_OF_WEEK) - 1
    //星期天:默认为0,重置为7
    if (w <= 0)
      w = 7
    w
  }

  /**
    * 获取过去第N天的日期(- N) 或者 未来 第几天的日期( N )
    *
    * @param past
    * @return
    */
  def getPastDate(past: Int) = {
    val calendar = Calendar.getInstance
    calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past)
    val today = calendar.getTime
    val format = new SimpleDateFormat("yyyyMMdd")
    val result = format.format(today)
    //          Log.e(null, result)
    result
  }

  def main(args: Array[String]): Unit = {
    val string: String = new DateTime(1487519989455l).toString("yyyy-MM-dd hh:mm:ss")
    //    println(Days.daysBetween(new DateTime(1488186015539l),new DateTime()).getDays <= 30)
    println(string)
  }

}
